$(function () {
    let thisID = '';// 当前轮次ID
    let activeIndex = -1 ;// 轮数
    let itemInfo = '';

    initPage();
    function initPage() {
        let Pr_itemRacetype = new Promise( (resolve,reject)=>{
            $.ajax({
                url : '/manage/racetypesamsara/list_racetype_samsara.do',
                type : 'post',
                data : getSearchInfo(),
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        resolve( data );
                    }else {
                        reject( data );
                    }
                }
            });
        });
        let Pr_itemRaceInfo = new Promise( (resolve,reject)=>{
            $.ajax({
                url : '/manage/racetypedetails/details.do',
                type : 'post',
                data : getSearchInfo(),
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        resolve( data);
                    }else {
                        reject( data );
                    }
                }
            });
        });
        let Pr_all = Promise.all([Pr_itemRacetype,Pr_itemRaceInfo]);
        Pr_all.then((data)=>{
            let itemRacetype = data[0].data,
                itemRaceInfo = data[1];
            if( itemRacetype.length ){
                $('.table-responsive').css( 'display' , 'block' );
                $('.itemNone').css('display','none');
                To_samsaraInfo(itemRacetype);
            }else{
                $('.table-responsive').css( 'display' , 'none' );
                $('.itemNone').css('display','block');
            }

            if( itemRaceInfo ){
                To_itemTypeInfo(itemRaceInfo);
            }
            console.log($('#sbsbsb'));
            $('#sbsbsb').css('display','inline-block');
            if(document.location.host==80){
            	$('#urlVoter').html(`http://${document.domain}/vote.html?racetypeno=${getSearchInfo()['racetypeno']}`);
            }else{
            	$('#urlVoter').html(`http://${document.location.host}/vote.html?racetypeno=${getSearchInfo()['racetypeno']}`);
            }
            
        }).catch( (data)=>{
            if( data.status == 10 ){
                spop_waring(data.msg,function () {},outLogin );
            }
            // else {
            //     spop_er(data.msg);
            // }
        });
    }

    // 添加轮次
    $('#newSamsara-model').on('show.bs.modal',function () {
        $(this).find('#myModalLabel').find('strong').text( $('#table-body').find('tr').length+1 );
    });
    $('#new-OK-btn').on('click',function () {
        let that = $(this);
        let thisModel = $('#newSamsara-model');
        let titleInput = $('#newSamsaraName-model').val().trim();
        if( titleInput ){
            that.attr('disabled',true);
            $.ajax({
                url : '/manage/racetypesamsara/add.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno,
                    racetypesamsaraname : titleInput,
                    ballotstarttime : $('#newStatrtTime-model').val(),
                    ballotstoptime : $('#newEndTime-model').val()
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok(data.msg, function () {
                            initPage();
                            thisModel.modal('toggle');
                            $('#newSamsaraName-model').val('');
                            $('#newStatrtTime-model').val('');
                            $('#newEndTime-model').val('');
                        },function () {
                            that.attr('disabled',false);
                        });
                    }else if(data.status == 10){
                        spop_waring(data.msg,function () {}, outLogin );
                    }else {
                        spop_er(data.msg);
                    }
                }
            });
        }else{
            spop_waring('请输入轮次名称');
        }
    });

    // 修改轮次
    $('#changeSamsaraModel').on('show.bs.modal',function (e) {
        let title = $(e.relatedTarget).parents('tr').children('td').eq(1).find('strong').html();
        let startTime = $(e.relatedTarget).parents('tr').children('td').eq(3).html();
        let endTime = $(e.relatedTarget).parents('tr').children('td').eq(4).html();
        thisID = $(e.relatedTarget).parents('tr').attr('data-id');
        $(this).find('#racetypesamsaraname-model').val( title );
        $(this).find('#ballotstarttime-model').val( startTime );
        $(this).find('#ballotstoptime-model').val( endTime );
    });
    $('#changeOk-model').on('click',function () {
        let info = $('#changeForm-model').serialize();
        info += '&racetypesamsarano='+ thisID;
        $.ajax({
            url : '/manage/racetypesamsara/update.do',
            type : 'post',
            data : info,
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                if( data.status == 0 ){
                    spop_ok(data.msg, function () {
                        initPage();
                        $('#changeSamsaraModel').modal('toggle');
                    });
                }else if(data.status == 10){
                    spop_waring(data.msg,function () {}, outLogin );
                }else {
                    spop_er(data.msg);
                }
            }
        });
    });

    // 删除轮次
    $('.table-responsive').on('click','.glyphicon-trash',function () {
        if( confirm('确定删除？') ){
            $.ajax({
                url : '/manage/racetypesamsara/delete.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno,
                    racetypesamsarano : $(this).parents('tr').attr('data-id')
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, initPage );
                    }else if( data.status == 10){
                        spop_waring( data.msg, function () {}, outLogin );
                    }else {
                        spop_er( data.msg );
                    }
                }
            });
        }
    });

    // 开启/关闭 本轮投票
    $('#table-body').on('click','.glyphicon-stats',function () {
        let that = $(this);
        let DOM = that.parents('tr');
        if( Number( DOM.attr('data-status') ) ){
            // 开启
            $.ajax({
                url : '/manage/racetypesamsara/ballot_start.do',
                type : 'post',
                data : {
                    racetypesamsarano : DOM.attr('data-id')
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, function () {
                            DOM.attr('data-status', '0');
                            DOM.find('.toggleStatus').removeClass('status-1').addClass('status-0').html('开启');
                            that.attr('data-original-title','投票已开启');
                        } );
                    }else if( data.status == 10){
                        spop_waring( data.msg, function () {}, outLogin );
                    }else {
                        spop_er( data.msg );
                    }
                }
            });
        }else{
            // 关闭
            $.ajax({
                url : '/manage/racetypesamsara/ballot_stop.do',
                type : 'post',
                data : {
                    racetypesamsarano : DOM.attr('data-id')
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok( data.msg, function () {
                            DOM.attr('data-status', 1);
                            DOM.find('.toggleStatus').removeClass('status-0').addClass('status-1').html('关闭');
                            that.attr('data-original-title','投票已关闭');
                        } );
                    }else if( data.status == 10){
                        spop_waring( data.msg, function () {}, outLogin );
                    }else {
                        spop_er( data.msg );
                    }
                }
            });
        }
    });

    // 添加项目类型信息
    $('#addItemTypeInfo').on('click',function () {
        let info = $('.itemTypeInfo').find('textarea').val().trim();
        if( info ){
            $.ajax({
                url : '/manage/racetypedetails/add.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno,
                    racetypedetailed : info
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok(data.msg, ()=>{
                            itemInfo = info;
                        });
                    }else if( data.status == 10 ){
                        spop_waring(data.msg,()=>{},outLogin);
                    }else{
                        spop_er(data.msg, function () {
                            $('.itemTypeInfo').find('textarea').val( itemInfo );
                        });
                    }
                }
            });
        }else{
            spop_waring('输入不能为空');
            $('.itemTypeInfo').find('textarea').focus();
        }
    });
    // 修改项目类型信息
    $('#reviseItemTypeInfo').on('click',function () {
        let info = $('.itemTypeInfo').find('textarea').val().trim();
        if( info ){
            $.ajax({
                url : '/manage/racetypedetails/update.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno,
                    racetypedetailed : info
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if( data.status == 0 ){
                        spop_ok(data.msg, ()=>{
                            itemInfo = info;
                        });
                    }else if( data.status == 10 ){
                        spop_ok(data.msg,()=>{},outLogin);
                    }else{
                        spop_er(data.msg);
                    }
                }
            });
        }else{
            spop_waring('输入不能为空');
            $('.itemTypeInfo').find('textarea').focus();
        }
    });

    // 开始当前轮次
    $('.container-fluid').on('click','.glyphicon-bullhorn',function () {
        let thisID = $(this).parents('tr').attr('data-id');
        $.ajax({
            url : '/manage/racetypedetails/set_level.do',
            type : 'post',
            data : {
                racetypeno : getSearchInfo().racetypeno,
                racetypesamsarano : thisID
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                if( data.status == 0 ){
                    spop_ok(data.msg , initPage );
                }else if( data.status == 10 ){
                    spop_ok(data.msg,()=>{},outLogin);
                }else{
                    spop_er(data.msg);
                }
            }
        });
    });

    // 开始下一轮比赛
    $('#playTurnMatch').on('click',function () {
        let length = $('#table-body').find('tr').length;
        if( length === activeIndex ){
            $.ajax({
                url : '/manage/racetypedetails/stop_level.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    if(data.status == 0 ){
                        spop_ok(data.msg, initPage );
                    }else if(data.status == 10){
                        spop_waring(data.msg,()=>{},outLogin);
                    }else{
                        spop_er(data.msg)
                    }
                }
            })
        }else{
            $.ajax({
                url : '/manage/racetypedetails/next_level.do',
                type : 'post',
                data : {
                    racetypeno : getSearchInfo().racetypeno
                },
                xhrFields : {
                    withCredentials: true
                },
                crossDomain: true,
                success : function (data) {
                    console.log(data);
                    if(data.status == 0 ){
                        spop_ok(data.msg,initPage);
                    }else if(data.status == 10){
                        spop_waring(data.msg,()=>{},outLogin);
                    }
                    // else if(data.status == 1 ){
                    //     playOne();
                    // }
                    else{
                        spop_er(data.msg)
                    }
                }

            })
        }
    });

    $('#votaPage').on('click', function () {
        let sb = getSearchInfo();
        window.location.href =  './../vote.html?racetypeno='+ sb['racetypeno']
    });

    function To_samsaraInfo(arr) {
        $('#table-body').html('');
        $(arr).each((idx,item)=>{
            console.log(item);
            let DOM =   $(' <tr data-id="'+ item.racetypesamsarano +'">' +
                '               <td class="text-center Text-fwb">第 <strong>'+ item.racetypesamsaragrade +'</strong> 轮</td>\n' +
                '               <td><strong>'+ item.racetypesamsaraname +'</strong></td>\n' +
                '               <td class="toggleStatus status-0"></td>\n' +
                '               <td class="ballotstarttime">'+ item.ballotstarttime +'</td>\n' +
                '               <td class="ballotstoptime">'+ item.ballotstoptime +'</td>\n' +
                '               <td class="itemTypeSetBox">\n' +
                '                   <i class="glyphicon glyphicon-pencil" data-toggle="modal" data-target="#changeSamsaraModel" data-whatever="@mdo"></i>\n' +
                '                   <i class="glyphicon glyphicon-stats" data-toggle="tooltip" data-placement="top" title="开启投票"></i>\n' +
                '                   <i class="glyphicon glyphicon-trash"></i>' +
                '                   <i class="glyphicon glyphicon-bullhorn"></i>' +
                '            </td>' +
                '         </tr>');

            DOM = setSamsaraStatus( DOM, item.ballotstatus );
            DOM = setSamsaraTime( DOM, item.ballotstarttime, item.ballotstoptime);

            $('#table-body').append(DOM);

            $('[data-toggle="tooltip"]').tooltip();
        });
    }

    function To_itemTypeInfo(data) {
        let obj = data.data;
        if( Boolean( obj ) ){
            let objName = obj.name;
            $('#itemTypeTitle').html(objName);
            let objInfo = obj.value;
            console.log(objInfo);
            $('.itemTypeInfo').find('textarea').val( objInfo.racetypedetailed );
            itemInfo = objInfo.racetypedetailed;
            $('#reviseItemTypeInfo').attr({
                'data-racetypeno' : objInfo.racetypeno,
                'data-racetypedetailsno' : objInfo.racetypedetailsno
            });
            $('#addItemTypeInfo').attr({
                'data-racetypeno' : objInfo.racetypeno,
                'data-racetypedetailsno' : objInfo.racetypedetailsno
            });

            if( objInfo.racetypedetailsstate === $('#table-body').find('tr').length ) {
                $('#playTurnMatch').html('结束比赛');
            }else{
                $('#playTurnMatch').html('开启下一轮比赛');
            }

            activeDOM_fn( objInfo.racetypedetailsstate );
        }
    }

    function setSamsaraStatus( DOM, status) {
        if( status ){
            DOM.find('.toggleStatus').addClass('status-1').text('关闭');
            DOM.find('.glyphicon-stats').attr('title','投票已关闭');
        }else{
            DOM.find('.toggleStatus').addClass('status-0').text('开启');
            DOM.find('.glyphicon-stats').attr('title','投票已开启');
        }
        DOM.attr('data-status',status);

        return DOM;
    }
    function setSamsaraTime( DOM, startTime, endTime ) {
        let startT = startTime ? startTime : '----:--:--' ;
        let endT = endTime ? endTime : '----:--:--' ;
        DOM.find('.ballotstarttime').text( startT );
        DOM.find('.ballotstoptime').text( endT );
        return DOM;
    }

    function playOne() {
        alert('开始比赛');
        let thisID = $('#table-body').find('tr').eq(0).attr('data-id');
        $.ajax({
            url : '/manage/racetypedetails/set_level.do',
            type : 'post',
            data : {
                racetypeno : getSearchInfo().racetypeno,
                racetypesamsarano : thisID
            },
            xhrFields : {
                withCredentials: true
            },
            crossDomain: true,
            success : function (data) {
                if( data.status == 0 ){
                    spop_ok('比赛开始' , initPage );
                }else if( data.status == 10 ){
                    spop_ok(data.msg,()=>{},outLogin);
                }else{
                    spop_er(data.msg);
                }
            }
        });
    }

    function activeDOM_fn(index) {
        let DOM = $('#table-body').find('tr').eq( eval(index-1) );
        console.log(index);
        console.log($('#table-body').find('tr'));
        DOM.siblings().each((i,item)=>{
            $(item).find('td').eq(1).find('span').remove();
        });

        if( index > 0 ){
            $('#itemTypeName').html( '(第<strong>' + index + '</strong>轮)' );
            DOM.find('td').eq(1).append( $('<span>(进行中)</span>') );
            activeIndex = index;
        }else{
            $('#itemTypeName').html('');
        }
    }
});